App.module.Page = Ext.extend(App.Module, {
	name: 'Pages'
	,init: function(){
		this.launcher = {
			text: this.name
			,handler: this.showWin
			,scope: this
		};
	}
	,getStore: function(){
		if(this.store) return this.store;
		this.store = new Ext.data.DirectStore({
			autoLoad: true
			,baseParams: {start: 0, limit: pageSize}
			,proxy: new Ext.data.DirectProxy({
				directFn: API.page.load	
			})
			,reader: new Ext.data.JsonReader({
				root: 'rows'
				,totalProperty: 'total'
			}, ['id', 'page_id', 'name', {name: 'created_time', type: 'int'}])
			,sortInfo: {
				field: 'name'
				,direction: 'ASC'	
			}
		});
		return this.store;
	}
	,getCm: function(){
		if(this.cm) return this.cm;
		
		this.cm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer({
				header: 'No.'
				,searchable: false	
			}),{
				header: '#'
				,dataIndex: 'page_id'
				,sortable: true
				,width: 50
				,fixed: true
				,hidden: true
			},{
				header: 'Name'
				,dataIndex: 'name'
				,sortable: true
				,defaultSearch: true
				,editor: new Ext.form.TextField({allowBlank: false, selectOnFocus: true})
			},{
				header: 'Time'
				,dataIndex: 'created_time'
				,sortable: true
				,width: 150
				,fixed: true
				,renderer: function(v){
					var date = new Date(v * 1000);
					return Ext.util.Format.date(date, App.Config.dateTimeFormat);
				}
			}
		]);
		return this.cm;
	}
	,getToolbar: function(){
		if(this.toolbar) return this.toolbar;
		
		this.toolbar = new Ext.Toolbar({
		});
		
		return this.toolbar;
	}
	,getGrid: function(){
		if(this.gird) return this.grid;
		
		var store = this.getStore();
		var cm = this.getCm();
		var toolbar = this.getToolbar();
		
		this.grid = new App.Grid({
			store: store
			,cm: cm
			,region: 'center'
			,tbar: toolbar
			,plugins: [
				new App.module.Page.Add()
				,new App.module.Page.Update()
				,new App.module.Page.Delete()
				,new App.module.Page.Search()
			]
			,listeners: {
				afteredit: function(o){
					var data = {
						page_id: o.record.data.page_id
					};
					data[o.field] = o.value;
					
					API.page.update(data, function(r){
						if(!r) Ext.Msg.alert('Error', 'Unknow error!');
						if(r.success) return o.record.commit();
						
						Ext.Msg.alert('Error', r.msg);
						o.record.reject();
					});
				}	
			}
		});
		return this.grid;
	}
	,getItems: function(){
		return [
			this.getGrid()
		];
	}
	,getWin: function(){
		if(!this.win){
			var items = this.getItems();
			this.win = new App.Window({
				id: this.id
				,title: this.name
				,iconCls: this.id + '-16x16'
				,layout: 'border'
				,items: items
			});	
		}
		return this.win;
	}
	,showWin: function(id){
		this.getWin().show(id);	
	}
});